<?php
namespace App\Support\Helper;

use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\Crypt;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\Printer;

/**
 * @Author:: HuangYin
 * @DateTime: 2017-03-09 10:17
 *
 * @Description:
 */

class CommonHelper
{
    // Encrypt
    public static function encrypt($encrypt = '')
    {
        if (empty($encrypt)) {
            return false;
        }

        return Crypt::encrypt($encrypt);
    }

    // Decrypt
    public static function decrypt($encrypt = '')
    {
        if (empty($encrypt)) {
            return false;
        }

        try {
            return Crypt::decrypt($encrypt);
        } catch (DecryptException $e) {

            return false;
        }
    }

    // Set Token
    public static function setToken($token)
    {
        return self::encrypt($token);
    }

    // Get Token
    public static function getToken($token)
    {
        $token = self::decrypt($token);
        $token = json_decode($token, true);
        if (is_array($token) && count($token) === 2) {
            return $token;
        }

        return null;
    }

    // Salt Password
    public static function hashPassword($salt, $password)
    {
        return md5($salt . $password);
    }

    // Filter Array
    public static function filterMap(array $data, $column = [''])
    {
        if (!is_array($data) || !$data || !$column) {
            return $data;
        }
        $result = [];
        foreach ($data as $keys => $value){
            foreach ($value as $key => $item) {
                if (in_array($key, $column)) {
                    $result[$keys][$key] = $item;
                }
            }
        }

        return $result;
    }

    /**
     * @param string $str
     */
    public static function printers($str = '')
    {
        $connector = new FilePrintConnector("php://stdout");
        $printer = new Printer($connector);
        $printer -> text($str);
        $printer -> cut();
        $printer -> close();
    }
}